package com.example.shop_front_api.controller;

import com.example.shop_front_api.constant.ShopConstant;
import com.example.shop_front_api.entity.Cart;
import com.example.shop_front_api.entity.Product;
import com.example.shop_front_api.service.CartService;
import com.example.shop_front_api.service.ProductService;
import com.example.shop_front_api.utils.JsonResult;
import com.example.shop_front_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CartService cartService;

    @PostMapping("add")
    public JsonResult addCart(@RequestBody Cart cart) {
        Integer productId = cart.getProductId();
        Product productInfo = productService.getProductById(productId);
        if (productInfo == null || productInfo.getStatus() != ShopConstant.PRODUCT_STATUS_ON) {
            return JsonResult.failed("该商品不存在或已下架");
        }

        int availableStock = Tool.getAvailableStock(productInfo.getStock(), productInfo.getLockStock());
        if (availableStock < 1) {
            return JsonResult.failed("该商品已售完");
        }

        Cart existingCart = cartService.getCart(cart.getMemberId(), cart.getProductId());
        if (existingCart == null) {
            cart.setCreatedTime(Tool.getCurrentTime());
            cart.setQuantity(1);
            cart.setSelected(ShopConstant.SELECTED_YES);
            cart.setPayPrice(productInfo.getPrice());
            int result = cartService.insertCart(cart);
            if (result > 0) {
                return JsonResult.success("添加购物车成功", null);
            } else {
                return JsonResult.failed("添加购物车失败");
            }
        } else {
            int result = cartService.updateCart(cart.getMemberId(), cart.getProductId(), 1);
            if (result > 0) {
                return JsonResult.success("更新购物车成功", null);
            } else {
                return JsonResult.failed("更新购物车失败");
            }
        }
    }

    @GetMapping("list")
    public JsonResult listCart(@RequestParam("member_id") Integer memberId) {
        List<Cart> cartList = cartService.getCartListByMemberId(memberId);
        for (Cart cart : cartList) {
            Product productInfo = productService.getProductById(cart.getProductId());
            if (productInfo != null) {
                cart.setProductName(productInfo.getProductName());
                cart.setProductImage(productInfo.getMainImage());
                if (productInfo.getStatus() != ShopConstant.PRODUCT_STATUS_ON) {
                    cart.setSelected(ShopConstant.SELECTED_NO);
                    cartService.updateSelectedById(cart.getId(), ShopConstant.SELECTED_NO);
                }
            }
        }
        return JsonResult.success("获取成功", cartList);
    }

    @GetMapping("total_amount")
    public JsonResult totalAmount(@RequestParam("member_id") Integer memberId) {
        List<Cart> results = cartService.getCartListByMemberIdSelected(memberId);
        if (results.isEmpty()) {
            return JsonResult.success("ok", 0);
        }
        Double totalAmount = cartService.getCartTotalAmount(memberId);
        return JsonResult.success("ok", totalAmount);
    }

    @GetMapping("delete")
    public JsonResult delete(@RequestParam("id") Integer id) {
        if (id <= 0) {
            return JsonResult.failed("删除失败,id不能为空");
        }
        int result = cartService.deleteCartProductById(id);
        if (result > 0) {
            return JsonResult.success("删除成功", null);
        } else {
            return JsonResult.failed("删除失败");
        }
    }

    @GetMapping("selected")
    public JsonResult selected(@RequestParam("id") Long id,
                               @RequestParam(value = "selected", defaultValue = "1") Integer selected) {
        if (id <= 0) {
            return JsonResult.failed("操作失败,id不能为空");
        }
        int result = cartService.updateSelectedById(id, selected);
        if (result > 0) {
            return JsonResult.success("操作成功", null);
        } else {
            return JsonResult.failed("操作失败");
        }
    }

    @GetMapping("selected_all")
    public JsonResult selectedAll(@RequestParam("ids") String ids,
                                  @RequestParam(value = "selected", defaultValue = "1") Integer selected) {
        if (ids.isEmpty()) {
            return JsonResult.failed("操作失败,id不能为空");
        }

        String safeIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(s -> s.matches("\\d+"))
                .collect(Collectors.joining(","));

        if (safeIds.isEmpty()) {
            return JsonResult.failed("操作失败,参数格式错误");
        }

        String idsSql = "(" + safeIds + ")";
        int result = cartService.batchUpdateSelected(idsSql, selected);
        if (result > 0) {
            return JsonResult.success("操作成功", null);
        } else {
            return JsonResult.failed("操作失败");
        }
    }

    @PostMapping("update_quantity")
    public JsonResult updateQuantity(@RequestParam("id") Integer id,
                                     @RequestParam("product_id") Integer productId,
                                     @RequestParam("quantity") Integer quantity) {
        if (id <= 0) {
            return JsonResult.failed("更新失败,id不能为空");
        }

        if (quantity <= 0 || quantity > ShopConstant.QUANTITY_MAX) {
            return JsonResult.failed("数量必须在1-" + ShopConstant.QUANTITY_MAX + "之间");
        }

        Product productInfo = productService.getProductById(productId);
        if (productInfo == null || productInfo.getStatus() != ShopConstant.PRODUCT_STATUS_ON) {
            return JsonResult.failed("该商品不存在或已下架");
        }

        int availableStock = Tool.getAvailableStock(productInfo.getStock(), productInfo.getLockStock());
        if (availableStock < quantity) {
            return JsonResult.failed("库存不足，当前可用库存：" + availableStock);
        }

        int result = cartService.updateCartQuantity(id, quantity);
        if (result > 0) {
            return JsonResult.success("更新成功", null);
        } else {
            return JsonResult.failed("更新失败");
        }
    }
}